<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <el-select
      v-model="listQuery.area"
      style="width: 200px"
      class="filter-item"
      placeholder="请选择乡镇"
    >
      <el-option v-for="(key,index) in areas" :key="index" :label="key.areaName" :value="key.areaName" />
    </el-select>
    <el-input
      v-model="listQuery.shopName"
      clearable
      class="filter-item"
      style="width: 200px;"
      placeholder="请输入项目名称"
    />
    <el-input
      v-model="listQuery.shigongdanwei"
      clearable
      class="filter-item"
      style="width: 200px;"
      placeholder="请输入施工单位"
    />
    <el-input
      v-model="listQuery.jianlidanwei"
      clearable
      class="filter-item"
      style="width: 200px;"
      placeholder="请输入监理单位"
    />
    <el-button
      v-permission="['system:user:query']"
      class="filter-item"
      type="primary"
      icon="el-icon-search"
      @click="handleFilter"
    >查找</el-button>
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加项目</el-button>
    </div>
    <div id="qrcode" style="display: none;"/>
    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="shopName" align="center" label="项目名称" />
      <el-table-column prop="area" align="center" label="乡镇" />
      <el-table-column prop="pianarea" align="center" label="片区" />
      <el-table-column prop="biaoduan" align="center" label="标段" />
      <el-table-column prop="fuzerenname" align="center" label="现场负责人" />
      <el-table-column prop="jianliname" align="center" label="监理" />
      <el-table-column prop="xiangzhenname" align="center" label="乡镇负责人" />
      <el-table-column prop="cunname" align="center" label="村负责人" />
      <el-table-column prop="shopQrcode" align="center" label="二维码">
        <template slot-scope="scope">
          <el-image :src="scope.row.shopQrcodeUrl" :preview-src-list="[...scope.row.shopQrcodeUrl]"/>
          <a ref="locatorQRCodeDownloadLinkRef" style="display: none"/>
          <div style="color: coral; cursor: pointer; margin-top: -12px;" @click="handleDownloadLocatorQRCode(scope.row)">点击下载</div>
        </template>
      </el-table-column>
      <el-table-column prop="jindu" align="center" label="进度" >
        <template slot-scope="scope">
          {{ scope.row.jindu>0?(scope.row.jindu * 100).toFixed(0)+'%':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="trueName" align="center" label="创建人" />
      <el-table-column prop="gmtCreate" align="center" label="创建时间" >
        <template slot-scope="scope"><el-col>{{ scope.row.gmtCreate | formatGmt }}</el-col></template>

      </el-table-column>
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--          <el-button
            v-permission="['admin:userShop:update']"
            v-if="scope.row.status === 0"
            type="primary"
            size="mini"
            @click="handleStatus(scope.row)"
          >完成</el-button
          >-->
          <el-button
            v-permission="['admin:file:list']"
            style="margin-bottom: 10px;"
            type="primary"
            size="mini"
            @click="handleToLink('/usershop/file?shopId='+scope.row.id+'&shopName='+scope.row.shopName)"
          >文件管理</el-button>
          <el-button
            v-permission="['admin:cailiaoPici:list']"
            style="margin-bottom: 10px;"
            type="primary"
            size="mini"
            @click="handleToLink('/cailiao/cailiaopici?shopId='+scope.row.id+'&shopName='+scope.row.shopName)"
          >物料管理</el-button>
          <el-button
            v-permission="['admin:shopBiaozhun:list']"
            style="margin-bottom: 10px;"
            type="primary"
            size="mini"
            @click="handleToLink('/shopBiaozhun/shopBiaozhun?shopId='+scope.row.id+'&shopName='+scope.row.shopName)"
          >工程管理</el-button>
          <el-button
            v-permission="['admin:gongchengLog:list']"
            style="margin-bottom: 10px;"
            type="primary"
            size="mini"
            @click="handleToLink('/shopDiscuss/log?shopId='+scope.row.id+'&shopName='+scope.row.shopName)"
          >施工管理</el-button>
          <el-button
            v-permission="['admin:log:list']"
            style="margin-bottom: 10px;"
            type="primary"
            size="mini"
            @click="handleToLink('/shopone/log?shopId='+scope.row.id+'&shopName='+scope.row.shopName)"
          >监理管理</el-button>
          <!--            <router-link :to="'/usershop/file?shopId='+scope.row.id+'&shopName='+scope.row.shopName">文件管理</router-link>
          <router-link :to="'/cailiao/cailiaopici?shopId='+scope.row.id+'&shopName='+scope.row.shopName">资料管理</router-link>
          <router-link :to="'/shopBiaozhun/shopBiaozhun?shopId='+scope.row.id+'&shopName='+scope.row.shopName">工程管理</router-link>
          <router-link :to="'/shopDiscuss/log?shopId='+scope.row.id+'&shopName='+scope.row.shopName">施工管理</router-link>
          <router-link :to="'/shopone/log?shopId='+scope.row.id+'&shopName='+scope.row.shopName">监理管理</router-link>
         -->
          <el-button
            v-permission="['admin:userShop:update']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button
          >
          <!--<el-button
            v-permission="['admin:userShop:update']"
            type="info"
            size="mini"
            @click="handleDetail(scope.row)"
          >查看</el-button>-->
          <el-button
            v-permission="['admin:userShop:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="" prop="id" style="display: none">
          <el-input v-model="dataForm.id" type="hidden" />
        </el-form-item>
        <el-form-item label="乡镇" prop="areaId">
          <el-select
            v-model="dataForm.areaId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择乡镇" >
            <el-option v-for="(item,index) in areas" :key="index" :label="item.areaName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="片区" prop="pianarea">
          <el-input v-model="dataForm.pianarea" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="标段" prop="biaoduan">
          <el-input v-model="dataForm.biaoduan" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="施工单位" prop="shigongdanwei">
          <el-input v-model="dataForm.shigongdanwei" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="项目经理" prop="businessLicence">
          <el-autocomplete
            v-model="dataForm.xiangmujingliname"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            class="inline-input"
            placeholder="请输入内容"
            @select="handleSubmitxiangmuid"
          />
        </el-form-item>
        <el-form-item label="现场负责人" prop="fuzerenname">
          <el-autocomplete
            v-model="dataForm.fuzerenname"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            class="inline-input"
            placeholder="请输入内容"
            @select="handleSubmitFuzeren"
          />
        </el-form-item>
        <el-form-item label="监理单位" prop="jianlidanwei">
          <el-input
            v-model="dataForm.jianlidanwei"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="项目总监" prop="jianlizongjianName">
          <el-autocomplete
            v-model="dataForm.jianlizongjianName"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            class="inline-input"
            placeholder="请输入内容"
            @select="handleSubmitJianliZongjian"
          />
        </el-form-item>
        <el-form-item label="监理" prop="jianliname">
          <el-autocomplete
            v-model="dataForm.jianliname"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            class="inline-input"
            placeholder="请输入内容"
            @select="handleSubmitJinali"
          />
        </el-form-item>
        <el-form-item label="乡镇负责人" prop="xiangzhenname">
          <el-input v-model="dataForm.xiangzhenname" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="乡镇负责人联系方式" prop="xiangzhenphone">
          <el-input v-model="dataForm.xiangzhenphone" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="村负责人" prop="cunname">
          <el-input v-model="dataForm.cunname" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="村负责人联系方式" prop="cunphone">
          <el-input v-model="dataForm.cunphone" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="二维码编号" prop="shopQrcode">
          <el-input v-model="dataForm.shopQrcode" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="经度" prop="jingdu">
          <el-input v-model="dataForm.jingdu" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="维度" prop="weidu">
          <el-input v-model="dataForm.weidu" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="面积" prop="mianji">
          <el-input v-model="dataForm.mianji" clearable placeholder="">
            <template slot="append">亩</template>
          </el-input>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="dataForm.money" clearable placeholder="">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dataForm.status" clearable style="width: 200px" class="filter-item" placeholder="请选择状态" >
            <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
        >确定</el-button
        >
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="renzheng" title="审批">
      <el-form label-width="100px">
        <el-form-item :label="renzhengTit">
          <el-radio-group v-model="status">
            <el-radio :label="1">同意</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因">
          <el-input v-model="reason" clearable />
        </el-form-item>
        <div class="dialog-footer" style="text-align: right;">
          <el-button type="primary" @click="tapRenzheng">认证</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<style>
.fixed-width .el-button--mini {
  width: auto !important;
  min-width: 60px;
}
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import {
  list,
  create,
  del,
  update,
  active,
  activeBusinessStatus,
  activeIdentityStatus
} from '@/api/usershop'
import { queryListByName } from '@/api/admin'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import QRCode from 'qrcodejs2'
import { selectArea } from '@/api/frontutil'

export default {
  name: 'UserShop',
  components: { Pagination },
  filters: {},
  data() {
    return {
      areas: [],
      statusMap: [{ value: 0, name: '未开始' }, { value: 1, name: '进行中' }, { value: 2, name: '已完成' }],
      list: undefined,
      total: 0,
      listLoading: true,
      academyData: [],
      academyName: '',
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined
      },
      options: [],
      dataForm: {
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {},
      renzheng: false,
      renzhengTit: '',
      statusType: '',
      renzhengData: '',
      status: 0,
      reason: ''
    }
  },
  created() {
    this.getList()
    this.listArea()
  },
  methods: {
    listArea() {
      selectArea()
        .then(response => {
          this.areas = response.data.data
          console.log(this.areas)
        })
        .catch(() => {
        })
    },
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.list.forEach(item => {
            const qrCodeUrl = 'https://jianli.jiashengqizhi.com?qrCode=' + item.shopQrcode
            const qrCodeImage = new QRCode(document.getElementById('qrcode'), {
              text: qrCodeUrl,
              width: 120,
              height: 120,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.L
            })
            console.log(qrCodeImage, '=====qrCodeImage')
            item.shopQrcodeUrl = qrCodeImage._oDrawing._elCanvas.toDataURL('image/png')
          })
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 下载二维码功能
    handleDownloadLocatorQRCode(row) {
      const downloadLink = this.$refs.locatorQRCodeDownloadLinkRef
      downloadLink.setAttribute('href', row.shopQrcodeUrl)
      console.log('this.qrcodeImgUrl', row.shopQrcodeUrl)
      downloadLink.setAttribute(
        'download',
        `二维码_${new Date().getTime()}.png`
      )
      downloadLink.click()
      URL.revokeObjectURL(downloadLink.href)
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined

      }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleStatusCom(row, type) {
      this.renzheng = true
      this.statusType = type
      this.renzhengData = row
      this.resetForm()
      if (type === 'Identity') {
        this.renzhengTit = '实人认证：'
      } else if (type === 'Business') {
        this.renzhengTit = '企业认证：'
      }
    },
    tapRenzheng() {
      this.renzheng = false
      var type = this.statusType
      var row = this.renzhengData
      if (type === 'Identity') {
        this.handleIdentityStatus(row)
      } else if (type === 'Business') {
        this.handleBusinessStatus(row)
      }
    },
    handleBusinessStatus(row) {
      // this.dataForm.id = row.id;
      // this.dataForm.status = this.status;
      activeBusinessStatus({
        id: row.id,
        status: this.status,
        reason: this.reason
      })
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleIdentityStatus(row) {
      // this.dataForm.id = row.id;
      // this.dataForm.status = this.status;
      activeIdentityStatus({
        id: row.id,
        status: this.status,
        reason: this.reason
      })
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.shopQrcode = new Date().getTime()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      create(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      update(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '更新成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        })
        .catch(() => {
          return false
        })
    },
    handleSubmitxiangmuid(item) {
      this.dataForm.xiangmujingliid = item.name
      this.dataForm.xiangmujingliname = item.value

      // 根据自身情况
      // 该方法是提交时触发
    },
    handleSubmitFuzeren(item) {
      debugger
      this.dataForm.fuzerenid = item.name
      this.dataForm.fuzerenname = item.value

      // 根据自身情况
      // 该方法是提交时触发
    },
    handleSubmitJinali(item) {
      this.dataForm.jianliId = item.name
      this.dataForm.jianliname = item.value

      // 根据自身情况
      // 该方法是提交时触发
    },
    handleSubmitJianliZongjian(item) {
      this.dataForm.jianlizongjianId = item.name
      this.dataForm.jianlizongjianname = item.value

      // 根据自身情况
      // 该方法是提交时触发
    },
    handleSubmitXiangzhen(item) {
      this.dataForm.xiangzhenId = item.name
      this.dataForm.xiangzhenname = item.value

      // 根据自身情况
      // 该方法是提交时触发
    },
    handleSubmitCun(item) {
      this.dataForm.cunId = item.name
      this.dataForm.cunname = item.value
      // 根据自身情况
      // 该方法是提交时触发
    },
    handleToLink(url) {
      this.$router.push({ path: url })
    },
    // 输入框获取焦点时调用的方法
    querySearch(queryString, cb) {
      // allInfos是怎么来，是从父组件传过来的还是在自己组件调用api接口拿到的还是其他
      // 我这里的allInfos是从父组件传过来的，在这里也举例子组件从父组件传值
      if (queryString !== '') { // 输入框中有值
        this.loadAacdemy(queryString, (data) => {
          console.log(data)
          var results = queryString ? data.filter(this.createFilter(queryString)) : data
          clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            cb(results)
          }, 5000 * Math.random())
        })
      }
    },
    // 该方法仿写官方文档，如果没有特别的需求，该方法改动不大
    // 这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
    // 我这里用的是调用match方法，是模糊匹配；官方调用的是indexOf，是精确匹配，看自身情况选择
    createFilter(queryString) {
      return (item) => {
        return item.value.toUpperCase().match(queryString.toUpperCase())
      }
    },
    loadAacdemy(query, fun) { // 后台根据用户输入的内容进行模糊查询
      const academies = []
      queryListByName({ 'trueName': query })
        .then(response => {
          const code = response.data.errno
          if (code === 200) {
            this.academyData = response.data.data
            console.log(this.academyData)
            if (this.academyData.length > 0) {
              this.academyData.forEach((item) => {
                academies.push({
                  value: item.realname,
                  name: item.id
                })
              })
            } else {
              academies.push({
                value: '未找到相关结果',
                name: '未找到相关结果'
              })
            }
            fun(academies)
          }
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    }
  }
}
</script>
